<?php
class Subscribe_Push_UserList
{
	protected $_style;
	
	public function __construct($style = null)
	{
		$this->_style = $style;
	}
	
	public function getUserList()
	{
		$authUser = Dzl_Db_Factory::getInstance()
			->createSelect()
			->from('dzl_alert_users', '*')
			->where('enddate>=?', date('Y-m-d'))
			->query()
			->fetchAll();
		
		$userList = array();
		foreach ($authUser as $user) {
			$mapUser = Dzl_Db_Factory::getInstance()
				->createSelect()
				->from('dzl_user', '*')
				->where('userid=?', $user['userid'])
				->query()
				->fetch();
			
			if ($this->_style == null) {
				//获取所有的用户
				$userList[] = $user;
			} else {
				//检查理念
				if ($mapUser['tzln1'] == $this->_style || $mapUser['tzln2'] == $this->_style) {
					$userList[] = $user;
				}
			}
		}
		return $userList;
	}
	
	public function setUserList($userList)
	{
		if (is_array($userList)) {
			foreach ($userList as $user) {
				if (!isset($user['username']) || !isset($user['userid']) 
				|| !isset($user['enddate']) || !isset($user['msgcode'])) {
					return array(
						'errorcode' => -1,
						'errormsg' => 'items omit some columns'
					);
				}
				$time = date('Y-m-d H:i:s');
				$default = array(
					'mtime' => $time,
				);			
				$binds = array_merge($default, $user);
				$where = array('userid=?' => $user['userid']);
				//先更新
				$table = Dzl_Db_Factory::getInstance()->createTable('dzl_alert_users');
				$rtn = $table->update($binds, $where);
				//如果更新失败就插入
				if (!$rtn) {
					try {
						$binds['ctime'] = $time;
						$rtn = $table->insert($binds);
						if (!$rtn) {
							return array(
								'errorcode' => -2,
								'errormsg' => 'database failed'
							);
						}
					} catch (Zend_Exception $e) {
						return array(
							'errorcode' => -3,
							'errormsg' => $e->getMessage()
						);
					}
				}
			}
			return array(
				'errorcode' => 0,
				'errormsg' => 'success'
			);
		} else {
			return array(
				'errorcode' => -4,
				'errormsg' => 'please input parameters'
			);
		}
	}
}